package com.tianhua.amis4j.service.admin;

import com.alibaba.fastjson.JSON;
import com.coderman.model.meta.bean.back.ApiBean;
import com.coderman.model.meta.bean.support.PageBean;
import com.tianhua.amis4j.infrast.dataobject.WebApiDO;
import com.tianhua.amis4j.infrast.mapper.WebApiMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * date: 2022/4/26
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class ApiConfigService {

    @Resource
    private WebApiMapper webApiMapper;

    /**
     * 保存webApi元信息
     * @param apiBean
     */
    public void saveApiConfig(ApiBean apiBean){
        WebApiDO  webApiDO = new WebApiDO();
        BeanUtils.copyProperties(apiBean,webApiDO);
        webApiDO.setRequestParam(JSON.toJSONString(apiBean.getParamBeanList()));
        webApiMapper.insert(webApiDO);
    }

    public void updateApiConfig(ApiBean apiBean){
        WebApiDO webApiDO = new WebApiDO();
        BeanUtils.copyProperties(apiBean,webApiDO);
        webApiMapper.update(webApiDO);
    }

    public PageBean selectPage(PageBean pageBean){
        List<WebApiDO> webApiDOList = webApiMapper.getPageList(pageBean);
        List<ApiBean> apiBeanList = new ArrayList<>();
        for (WebApiDO webApiDO : webApiDOList){
            ApiBean moduleBean = new ApiBean();
            BeanUtils.copyProperties(webApiDO,moduleBean);
            apiBeanList.add(moduleBean);
        }
        pageBean.setCount(webApiMapper.getPageCount(pageBean));
        pageBean.setRows(apiBeanList);
        return pageBean;
    }


    public List<ApiBean> getByModuleCode(String moduleCode){
        List<WebApiDO> webApiDOList = webApiMapper.getByModuleCode(moduleCode);
        List<ApiBean> apiBeanList = new ArrayList<>();
        for (WebApiDO webApiDO : webApiDOList){
            ApiBean apiBean = new ApiBean();
            BeanUtils.copyProperties(webApiDO,apiBean);
            apiBean.buildParam();
            apiBeanList.add(apiBean);
        }
        return apiBeanList;
    }


    public ApiBean getById(Long id){
        WebApiDO webApiDO = webApiMapper.getById(id);
        ApiBean apiBean = new ApiBean();
        BeanUtils.copyProperties(webApiDO,apiBean);
        return apiBean;
    }


    public void  delete(Long id){
        webApiMapper.deleteById(id);
    }

}
